//
//  BN_SchoolIntroductionViewController.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-5-15.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_SchoolIntroductionViewController.h"
#define TITLE_FONT 22
#define CONTENT_FONT 17

@interface BN_SchoolIntroductionViewController () {
    NSString *titleStr_;
    NSString *contentStr_;
    
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    BN_KinderGartenHelper *helper_;
    
    NSArray *netArr_;
}

// 标题
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

// 图片内容
@property (weak, nonatomic) IBOutlet UIImageView *contImageView;

// 文字内容
@property (weak, nonatomic) IBOutlet UILabel *contLabel;

@end

@implementation BN_SchoolIntroductionViewController

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (IOS7) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [[NSUserDefaults standardUserDefaults] setInteger:INTRODUCTION forKey:USERDEFAULTS_KINDERSECTION];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    // UI
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
  
    [self schoolNavgationBar:1];
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"houtui"] style:UIBarButtonItemStylePlain target:self action:@selector(backRootVCtrl)];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.title = @"园所简介";
    userInfo = [BN_UserHelper unArchiverAccountInfo];
    titleStr_ = userInfo.schoName;
    
    // 下拉刷新
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = _schoolInductionTableView;
    header.delegate = self;
    _header = header;
    
    // 小球提示
    [self viewLoadHintView];

    // 网络通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(jianjieRefresh) name:KSENDSUCCESS_AFTER_JIANJIE_REFRESH object:nil];
    
    // helper类
    if (!helper_) {
        helper_ = [[BN_KinderGartenHelper alloc]init];
    }
    
    // 网络数组
    netArr_ = [[NSArray alloc]init];
    [self performSelectorInBackground:@selector(requestNetData) withObject:nil];
}

- (void)initTableView {
    // 列表
    self.schoolInductionTableView = [[UITableView alloc]init];
    switch (MAIN_VERSION) {
        case 6:
            self.schoolInductionTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-44);
            break;
        default:
            self.schoolInductionTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, FULLSCREEN_HEIGHT);
            self.schoolInductionTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            self.schoolInductionTableView.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 0, 0);
            break;
    }
    [_schoolInductionTableView setDecelerationRate:0.1];
    _schoolInductionTableView.delegate = self;
    _schoolInductionTableView.dataSource = self;
    _schoolInductionTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_schoolInductionTableView];
}

#pragma mark Action
- (void)goCreateVC {
    BN_CreateContentViewController *createVC = [[BN_CreateContentViewController alloc]init];
    [createVC toHintMessage:^(BOOL isSuccess) {
        if (isSuccess) {
            [LZCHINT title:@"更新成功" type:LZCSuccess duration:2 places:HINT_PLACES callBack:NULL];
        }
    }];
    [self.navigationController pushViewController:createVC animated:YES];
}

#pragma mark
#pragma mark TableView Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NurserySchoolCellTableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
#warning bug cellHiehgt-30
    return cell.cellHeight-25;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"NurserySchoolCellTableViewCell";
    NurserySchoolCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"NurserySchoolCellTableViewCell" owner:nil options:nil]objectAtIndex:0];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    
    // files
    if (netArr_.count > 0) {
        NSArray *files = netArr_[0][@"files"];
        if (files.count > 0) {
            cell.dividerView.hidden = YES;
            cell.dividerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 0);
            cell.titleLabel.text = titleStr_;
            
            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
            paragraphStyle.lineSpacing = 4;
            NSDictionary *attributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:CONTENT_FONT], NSParagraphStyleAttributeName:paragraphStyle};
            cell.contLabel.attributedText = [[NSAttributedString alloc]initWithString:FORMAT_STR(netArr_[indexPath.row][@"cont"]) attributes:attributes];
            
            // 图片
            NSArray *files = netArr_[indexPath.row][@"files"];
            NSString *imgUrlStr = [THUMBNAIL_BASEURL stringByAppendingString:files[indexPath.row][@"fileTUrl"]];
            NSURL *imgURL = [NSURL URLWithString:imgUrlStr];
            [cell.contImageView setImageWithURL:imgURL placeholderImage:nil];
            [cell toGroup];
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark
#pragma mark 请求网络数据

- (void)jianjieRefresh {
    if (!helper_) {
        helper_ = [[BN_KinderGartenHelper alloc]init];
    }
    [self requestNetData];
}

- (void)requestNetData {
    __weak typeof(self) weakSelf = self;
    [helper_ queryKgDetail:^(id result, NSString *errMsg) {
        //update by jason yan 2014-05-30
        if (errMsg) {
            [LZCHINT title:errMsg type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
            [weakSelf cancelHintView];
        }
        if(result){
            netArr_ = (NSArray *)result;
            [weakSelf cancelHintView];
            [weakSelf initTableView];
        }
    }];
}


#pragma mark
#pragma mark 刷新类
- (void)upLoadFinished:(MJRefreshBaseView *)refreshView {
    // 列表开始加载，开始数据请求
    // [self loadNextNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 列表开始刷新，开始数据请求
    [self requestNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if (_header == refreshView) {
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:0.85];
    }else {
        [self performSelector:@selector(upLoadFinished:) withObject:refreshView afterDelay:0];
    }
}

- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
    // NSLog(@"%@----刷新完毕", refreshView.class);
}

- (void)refreshView:(MJRefreshBaseView *)refreshView stateChange:(MJRefreshState)state
{
    switch (state) {
        case MJRefreshStateNormal:
            // NSLog(@"%@----切换到：普通状态", refreshView.class);
            break;
            
        case MJRefreshStatePulling:
            // NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
            break;
            
        case MJRefreshStateRefreshing:
            // NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
            break;
        default:
            break;
    }
}

#pragma mark
#pragma mark 内存管理

- (void)releaseResource {
    
    helper_ = nil;
    
    [_header free];
    _header.delegate = nil;
    _header = nil;
    
    self.schoolInductionTableView.delegate = nil;
    self.schoolInductionTableView.dataSource = nil;
    self.schoolInductionTableView = nil;
    
    [self cancelHintView];
}

- (void)dealloc
{
    [self releaseResource];
    NSLog(@"学校简介释放...");
}

- (void)backRootVCtrl {
    
    [self releaseResource];
    [self.navigationController popViewControllerAnimated:YES];
}

@end
